package com.ruoyi.web.core.config;

import com.alibaba.druid.wall.violation.ErrorCode;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.*;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableSwagger2
@EnableKnife4j
public class Knife4jConfiguration {

    /**
     * 系统基础配置
     */
    @Autowired
    private RuoYiConfig gujiConfig;

    /**
     * 是否开启swagger
     */
    @Value("${swagger.enabled}")
    private boolean enabled;

    // 令牌自定义标识
    @Value("${token.header}")
    private String tokenHeader;

    /**
     * 设置请求的统一前缀
     */
//    @Value("${swagger.pathMapping}")
//    private String pathMapping;

    @Bean(value = "dockerBean")
    public Docket createRestApi() {
//        全局错误码
//        List<Response> globalCodes = getGlobalCodes();
        List<RequestParameter> globalParams = getGlobalParams();
        return new Docket(DocumentationType.OAS_30)
                .enable(enabled)
//                .globalResponses(HttpMethod.GET, globalCodes)
//                .globalResponses(HttpMethod.POST, globalCodes)
                .globalRequestParameters(globalParams)
                // 用来创建该API的基本信息，展示在文档的页面中（自定义展示的信息）
                .apiInfo(apiInfo())
                .groupName("Default")
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api，用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 这里指定Controller扫描包路径
                // .apis(RequestHandlerSelectors.basePackage("com.guji.web.controller.api"))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
                /* 设置安全模式，swagger可以设置访问token */
                //.securitySchemes(securitySchemes())
                //.securityContexts(securityContexts())
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("美甲接口文档")
                // 描述
                .description("美甲接口文档")
                // 作者信息
                .contact(new Contact(gujiConfig.getName(), null, "gxl3999@gmail.com"))
                // 版本
                .version("版本号:" + gujiConfig.getVersion())
                .build();
    }

    /**
     * 全局错误码
     */
//    private List<Response> getGlobalCodes() {
//        List<BaseResponse> errors = new ArrayList<>();
//        errors.add(ErrorCode.SUCCESS);
//        errors.add(ErrorCode.ERROR);
//        errors.add(ErrorCode.BAD_REQUEST);
//        errors.add(ErrorCode.FORBIDDEN);
//        Arrays.stream(PoaErrorEnums.values()).forEach(e -> {
//            if (e.isDoc == 1){
//                errors.add(e.data);
//            }
//        });
//        List<Response> codes = new ArrayList<>();
//        for (BaseResponse error : errors) {
//            codes.add(new ResponseBuilder().code(error.getCode().toString()).description(error.getMsg()).build());
//        }
//        return codes;
//    }

    /**
     * 全局参数
     */
    private List<RequestParameter> getGlobalParams() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name(tokenHeader)
                .description("登录令牌，没有传空")
                .required(false)
                .in(ParameterType.HEADER)
                .build());
        parameters.add(new RequestParameterBuilder()
                .name(Constants.LOGIN_UID)
                .description("自己的uid，没有传0")
                .required(false)
                .in(ParameterType.HEADER)
                .build());
        return parameters;
    }

    /**
     * 安全模式，这里指定token通过Authorization头请求头传递
     */
    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .operationSelector(o -> o.requestMappingPattern().matches("/.*"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

}